/* eslint-disable */
// Returns a unique image file name.
function getUniqueImageFileName(type) {
  return (
    'image-' + new Date().getTime() + parseInt(Math.random(20)) + '.' + type
  )
}

window.CKEDITOR.plugins.add('myImage', {
  onLoad:function(){
    CKEDITOR.document.appendStyleSheet(this.path + 'css/myimage.css')
  },
  init: function (editor) {
    var fileTools = window.CKEDITOR.fileTools,
      uploadUrl = fileTools.getUploadUrl(editor.config, 'image')

    if (!uploadUrl) {
      return
    }
    //监听paste事件，处理copy/paste图片(仅限本地base64格式图片资源，网络资源图片还未处理)
    editor.on('paste', function (evt) {
      const removePlugins = editor.config.removePlugins?.split(',') || []
      const flat =
      evt.data.dataTransfer.getFilesCount() > 0 || /<img/gi.test(evt.data.dataValue) || /<\/img/gi.test(evt.data.dataValue)
      const flag = ['myImage','uploadimage'].some(p=> removePlugins.includes(p)) //判断禁用部件中是否包含，对任一项返回true，则返回true
      if ( flag && flat) {
        evt.data.dataValue = evt.data.dataValue.replace(/<img.*?(?:>|\/>)/gi, '')
        // editor.showNotification('您拖拽或粘贴的内容含有图片，不允许拖拽或粘贴！', 'warning', 2000)
        return
      }
      editor.fire('unlockSnapshot') //解锁撤销快照记录
      // For performance reason do not parse data if it does not contain img tag and data attribute.
      if (!evt.data.dataValue.match(/<img[\s\S]+data:/i)) {
        return
      }

      var data = evt.data,
        // Prevent XSS attacks.
        tempDoc = document.implementation.createHTMLDocument(''),
        temp = new window.CKEDITOR.dom.element(tempDoc.body),
        imgs,
        img,
        i

      // Without this isReadOnly will not works properly.
      temp.data('cke-editable', 1)

      temp.appendHtml(data.dataValue)

      imgs = temp.find('img')

      for (i = 0; i < imgs.count(); i++) {
        img = imgs.getItem(i)

        // Assign src once, as it might be a big string, so there's no point in duplicating it all over the place.
        var imgSrc = img.getAttribute('src'),
          // Image have to contain src=data:...
          isDataInSrc = imgSrc && imgSrc.substring(0, 5) == 'data:',
          isRealObject = img.data('cke-realelement') === null
        // We are not uploading images in non-editable blocs and fake objects (https://dev.ckeditor.com/ticket/13003).
        if (
          isDataInSrc &&
          isRealObject &&
          !img.data('cke-upload-id') &&
          !img.isReadOnly(1)
        ) {
          // Note that normally we'd extract this logic into a separate function, but we should not duplicate this string, as it might
          // be large.
          var imgFormat = imgSrc.match(/image\/([a-z]+?);/i),
            loader
          imgFormat = (imgFormat && imgFormat[1]) || 'jpg'

          loader = editor.uploadRepository.create(
            imgSrc,
            getUniqueImageFileName(imgFormat)
          )

          loader.on('uploaded', function (evt) {
            editor.widgets.initOn(img, 'image', {
              src: evt.sender.url
            })
            img.setAttribute('src', evt.sender.url)
          })

          loader.on('error', function () {
            img.$ && img.$.remove()
          })
        }
      }

      data.dataValue = temp.getHtml()
    })
    editor.addCommand('myImage', {
      exec: function (editor) {
        let image = document.createElement('input')
        image.type = 'file'
        image.accept = 'image/*'
        image.click()
        image.addEventListener('change', async () => {
          let file = image.files[0]
          const formData = new FormData()
          let data = {
            file: file,
            module: editor.config.module
          }
          Object.keys(data).forEach(key => {
            formData.append(key, data[key])
          })
          var httpRequest = new XMLHttpRequest()
          var url = editor.config.filebrowserImageUploadUrl
          httpRequest.open('POST', url, true)
          httpRequest.setRequestHeader('token', editor.config.token)
          httpRequest.onload = function (e) {
            var res = JSON.parse(e.target.responseText)
            if (res.code === '00000') {
              const srcPath = editor.config.filebrowserImageDownloadUrl(res.data.module, res.data.path)
              editor.insertHtml(
                `<img src="${srcPath}" />`
              )
              editor.showNotification('文件上传成功', 'success', 2000)
            } else {
              editor.showNotification(`上传文件时发生错误（错误代码:${res.code}）`, 'warning')
            }
          }
          httpRequest.send(formData)
        })
      }
    })
    editor.ui.addButton('MyImage', {
      label: '添加图片',
      toolbar: 'insert',
      command: 'myImage'
    })
  }
})
